<template>
  <view class="date-picker">
    <scroll-view
      scroll-x
      class="scroll-area"
      :show-scrollbar="false"
      :enhanced="true"
      :scroll-left="scrollLeft"
      scroll-with-animation
      ref="scrollView"
      @scroll="handleScroll"
    >
      <view class="flex items-center h-30 px-3">
        <!-- 日期列表 -->
        <view
          v-for="(item, index) in visibleDates"
          :key="item.fullDate"
          :id="`date-${index}`"
          class="flex flex-col items-center justify-center w-[76px] h-[76px] mr-3 transition-all duration-300 relative"
          :class="[
            modelValue === item.fullDate
              ? 'bg-gradient-to-b from-orange-50 to-orange-100 shadow-sm'
              : 'bg-gray-50/80 active:scale-95',
          ]"
          @tap="handleSelect(item, index)"
        >
          <text
            class="text-base font-medium mb-1"
            :class="modelValue === item.fullDate ? 'text-orange-5' : 'text-gray-7'"
          >
            {{ item.weekday }}
          </text>
          <text
            class="text-xs font-medium"
            :class="modelValue === item.fullDate ? 'text-orange-4' : 'text-gray-5'"
          >
            {{ item.date }}
          </text>
          <view
            v-if="modelValue === item.fullDate"
            class="absolute -bottom-1 w-2 h-2 rounded-full bg-orange-5"
          />
        </view>

        <!-- 加载更多按钮 -->
        <view
          v-if="showLoadMore"
          class="flex items-center justify-center w-20 h-20 bg-white/90 shadow ml-3 rounded-full active:scale-95"
          @tap="loadMoreDates"
        >
          <view class="i-mdi-chevron-right text-gray-6 text-xl" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: String,
  startDate: {
    type: [String, Date],
    default: `${dayjs().startOf('day')}`,
  },
  endDate: [String, Date],
  visibleDays: {
    type: Number,
    default: 7,
  },
})

const emit = defineEmits(['update:modelValue', 'change', 'reach-end'])

// 数据状态
const currentStart = ref(dayjs(props.startDate))
const scrollLeft = ref(0)
const showLoadMore = ref(false)
const scrollView = ref(null)
const containerWidth = ref(375)

// 生成日期列表
const generateDates = (start, days) => {
  const dates = []
  const current = dayjs(start)

  for (let i = 0; i < days; i++) {
    if (props.endDate && current.isAfter(props.endDate)) break

    const date = current.add(i, 'day')
    dates.push({
      date: date.format('MM-DD'),
      weekday: date.format('dddd').replace('星期', '周'),
      fullDate: date.format('YYYY-MM-DD'),
      timestamp: date.valueOf(),
    })
  }

  return dates
}

// 当前可见日期
const visibleDates = computed(() => {
  return generateDates(currentStart.value, props.visibleDays)
})

// 处理日期选择
const handleSelect = async (item, index) => {
  emit('update:modelValue', item.fullDate)
  emit('change', item)

  await nextTick()
  scrollToCenter(index)
}

// 滚动到中间
const scrollToCenter = (index) => {
  const query = uni.createSelectorQuery().in(this)
  query.select(`#date-${index}`).boundingClientRect()
  query.select('.scroll-area').boundingClientRect()
  query.exec((res) => {
    if (!res[0] || !res[1]) return

    const itemRect = res[0]
    const scrollRect = res[1]
    const currentScroll = scrollView.value.scrollLeft

    const targetPosition = currentScroll + itemRect.left - scrollRect.width / 2 + itemRect.width / 2
    const maxScroll = scrollView.value.scrollWidth - scrollRect.width

    scrollLeft.value = Math.max(0, Math.min(targetPosition, maxScroll))
  })
}

// 加载更多日期
const loadMoreDates = () => {
  const newStart = currentStart.value.add(props.visibleDays, 'day')
  if (props.endDate && newStart.isAfter(props.endDate)) {
    emit('reach-end')
    return
  }

  currentStart.value = newStart
  showLoadMore.value = false
  nextTick(() => (scrollLeft.value = 0))
}

// 滚动处理
const handleScroll = (e) => {
  const { scrollWidth, scrollLeft, width } = e.detail
  showLoadMore.value = scrollLeft + width > scrollWidth - 50
}

// 初始化容器宽度
onMounted(() => {
  const query = uni.createSelectorQuery().in(this)
  query
    .select('.scroll-area')
    .boundingClientRect((res) => {
      if (res) containerWidth.value = res.width
    })
    .exec()

  if (!props.modelValue && visibleDates.value.length > 0) {
    emit('update:modelValue', visibleDates.value[0].fullDate)
  }
})

// 监听开始时间变化
watch(
  () => props.startDate,
  (val) => {
    currentStart.value = dayjs(val)
  },
)
</script>

<style lang="scss">
.date-picker {
  @apply w-full bg-white py-2;

  .scroll-area {
    @apply w-full whitespace-nowrap;

    &::-webkit-scrollbar {
      @apply hidden;
    }
  }
}
</style>
